<!--
 * @Author: windys
 * @Description: 西瓜播放器
 * @Date: 2022-03-09 09:32:52
-->
<template>
  <div class="xg_player">
    <div v-if="isBuy">
      <p>请先购买直播间</p>
      <van-button type="warning" size="small" round @click="handleOpenBuy"
        >购买直播间</van-button
      >
    </div>
    <div id="mse"></div>
  </div>

  <van-action-sheet v-model:show="showPay" title="购买直播间">
    <div class="content_send" v-if="list && list.length">
      <div class="title">购买赠送</div>
      <div class="item" v-for="item in list" :key="item.id">
        <div class="left">
          <van-image :src="item.coverUrl" width="120" radius="5px" />
        </div>
        <div class="right">
          <div class="titile">{{ item.goodsName }}</div>
          <div class="days">{{ item.days }}有效期</div>
          <div class="sp">
            <van-image
              :src="item.coverUrl"
              width="25"
              height="25"
              round
              fit="contain"
            />
            <span>{{ item.spName }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <van-button
        type="primary"
        size="small"
        plain
        round
        block
        @click="showPay = false"
        >取消</van-button
      >
      <van-button type="primary" size="small" round block @click="handlePay"
        >购买</van-button
      >
    </div>
  </van-action-sheet>

  <pwdDialog ref="pwdDialog" @handleCheckRoomPwdSucc="handleCheckRoomPwdSucc" />
</template>



<script>
import {
  computed,
  defineComponent,
  onBeforeUnmount,
  onMounted,
  ref,
  watch,
} from "vue";
import "xgplayer";
import HlsPlayer from "xgplayer-hls";
import { useRoute, useRouter } from "vue-router";
import {
  getShareLiveinfo,
  checkLivePwd,
  getSendGoodsList,
  payLive,
} from "@/api/live";
import { encruption } from "@/utils/index";
import storage from "@/utils/storage";
import { useStore } from "@/store";
import pwdDialog from "@/pages/live/pwdDialog.vue";
import { Toast, Dialog } from "vant";
export default defineComponent({
  components: {
    pwdDialog,
  },
  emits: ["changeShowBlackViweBtn"],
  setup(props, { emit }) {
    const router = useRouter();
    const route = useRoute();
    const store = useStore();

    onMounted(() => {
      init();
    });

    onBeforeUnmount(() => {
      if (myPlayer.value) {
        myPlayer.value.destroy();
      }
    });

    const myPlayer = ref();
    const pwdDialog = ref(); //密码
    const isBuy = ref(false);
    const c_csTabId = ref(null);
    const init = async () => {
      console.log('加载播放器....')
      // 未登录
      if (!storage.getStorage("v3_userinfo_mobile")) {
      console.log('加载播放器加载播放器加载播放器....')

        Dialog.alert({
          title: "提示",
          message: "直播间部分功能需要用户信息\n请登录后观看直播",
          confirmButtonColor: "#ee0a24",
          showCancelButton: true,
        })
          .then(() => {
            // on close
            emit('handleDisconnectChartRoom')
            setTimeout(()=>{
              router.push("/login");
            },1000)
          })
          .catch(() => {
            // on cancel
            emit('handleLeaveRoom')
          });
        return;
      }
      const pwds = JSON.parse(storage.getStorage("pwd"));
      const res = await getShareLiveinfo({
        liveId: route.query.liveId,
        pwd:
          route.query.isPwd == 1
            ? encodeURIComponent(encruption(pwds[route.query.liveId]))
            : false,
        type: 1,
      });
      if (typeof res === "object") {
        initPlayer(res.stream.httpPullUrl, res.coverUrl);
        isBuy.value = false;
        showPay.value = false;
        emit("changeShowBlackViweBtn", true, res.csTabId);
      } else if (res === 2004 || res === -200) {
        // 密码错误
        pwdDialog.value.liveId = route.query.liveId;
        pwdDialog.value.show = true;
        emit("changeShowBlackViweBtn", false, res.csTabId);
      } else if (res === 2001 || res === 2002) {
        // 需要付费
        c_csTabId.value = res.csTabId;
        isBuy.value = true;
        showPay.value = true;
        emit("changeShowBlackViweBtn", false, res.csTabId);
      }
    };

    const handleOpenBuy = () => {
      showPay.value = true;
    };

    // 初始化播放器
    const initPlayer = (url, coverUrl) => {
      myPlayer.value = new HlsPlayer({
        id: "mse",
        url: url,
        fluid: true,
        isLive: true,
        autoplay: !true,
        playsinline: true,
        poster: coverUrl,
        rotate: {
          //视频旋转按钮配置项
          innerRotate: true, //只旋转内部video
          clockwise: false, // 旋转方向是否为顺时针
        },
      });

      myPlayer.value.on("error", (res) => {
        console.log(res, "error");
        document.getElementsByClassName("xgplayer-error-text")[0].innerHTML =
          "主播暂时未开播";
        document.getElementsByClassName("xgplayer-error-text")[0].style.color =
          "red";
      });
      myPlayer.value.on("ended", (res) => {
        console.log(res, "ended");
      });
    };

    // 显示购买 赠送
    const showPay = ref(false);
    watch(
      () => showPay.value,
      (v) => {
        if (v) {
          initSendData();
        }
      }
    );
    const list = ref([]);
    const initSendData = async () => {
      const res = await getSendGoodsList({
        subjectId: route.query.liveId,
        pageIndex: 1,
        pageSize: 10,
      });
      if (res) {
        list.value = res;
      }
    };

    const handlePay = async () => {
      const res = await payLive({
        liveId: route.query.liveId,
        csTabId: c_csTabId.value,
      });
      if (typeof res === "string") {
        Toast.success("购买成功");
        init();
      }
      if (res === 1011) {
        store.openRecharge();
      }
    };

    // 密码成功
    const handleCheckRoomPwdSucc = (v) => {
      console.log(v);
      init();
    };
    return {
      c_csTabId,
      isBuy,
      list,
      store,
      myPlayer,
      showPay,
      pwdDialog,
      handlePay,
      init,
      initPlayer,
      handleOpenBuy,
      handleCheckRoomPwdSucc,
    };
  },
});
</script>



<style lang="scss" scoped>
.xg_player {
  border-bottom: 1px solid #00b7ff;
  height: 210px;
  overflow: hidden;
  background: #000;
  text-align: center;
  p {
    color: #fff;
    font-size: 14px;
    margin-top: 20%;
  }
}
.footer {
  display: flex;
  padding: 20px;
  justify-content: center;
  button {
    margin: 0 10px;
    width: 100px;
  }
}

.content_send {
  margin: 0 10px;
  font-size: 12px;
  overflow-y: auto;
  margin-top: 30px;
  max-height: 300px;
  .title {
    text-align: center;
    margin: 10px 0;
    font-size: 14px;
    color: #ff7b00;
  }
  .item {
    height: 80px;
    overflow: hidden;
    margin-bottom: 10px;
    display: flex;
    flex-direction: row;
    position: relative;

    .left {
      width: 120px;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .days {
      color: #ff7b00;
      text-align: right;
      border: 1px solid #ff7b00;
      display: inline;
      padding: 2px 5px;
      border-radius: 15px;
      position: absolute;
      font-size: 10px;
      right: 20px;
      top: 30px;
    }
    .right {
      width: calc(100% - 120px);
      padding: 4px 0;
      padding-left: 10px;
      .titile {
        font-size: 14px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .sp {
        display: flex;
        height: 30px;
        align-items: center;
        margin-top: 25px;
        span {
          font-size: 12px;
          color: #999;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>